package com.party.admin.biz.activity;

import cn.jpush.api.utils.StringUtils;
import com.google.common.collect.Maps;
import com.party.admin.biz.copartner.MemberCopartnerDetailBizService;
import com.party.admin.biz.distribution.DistributionBizService;
import com.party.admin.biz.refund.MessageOrderBizService;
import com.party.admin.biz.refund.RefundBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.output.activity.MemberActOutput;
import com.party.common.constant.Constant;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.counterfoil.CounterfoilType;
import com.party.core.model.gatherForm.GatherForm;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAct;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderStatus;
import com.party.core.model.order.OrderType;
import com.party.core.model.order.PaymentWay;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.OrderActivityBizService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.utils.MyBeanUtils;
import com.party.notify.notifyPush.servce.INotifySendService;
import com.party.pay.model.query.AliPayQueryResponse;
import com.party.pay.model.query.WechatPayQueryResponse;
import com.party.pay.model.refund.AliPayRefundResponse;
import com.party.pay.model.refund.WechatPayRefundResponse;
import com.party.pay.service.pay.PayOrderBizService;
import com.party.pay.service.refund.RefundOrderBizService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;

/**
 * 活动报名业务处理
 * Created by wei.li
 *
 * @date 2017/3/22 0022
 * @time 17:44
 */
@Service
public class MemberActBizService {

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private INotifySendService notifySendService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private PayOrderBizService payOrderBizService;

    @Autowired
    private MessageOrderBizService messageOrderBizService;

    @Autowired
    private OrderActivityBizService orderActivityBizService;

    @Autowired
    private RefundOrderBizService refundOrderBizService;

    @Autowired
    private RefundBizService refundBizService;

    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;

    @Autowired
    private IGatherProjectService gatherProjectService;

    @Autowired
    private IGatherFormService gatherFormService;

    @Autowired
    private IGatherFormInfoService gatherFormInfoService;

    @Autowired
    private ICounterfoilBusinessService counterfoilBusinessService;

    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;

    @Autowired
    private DistributionBizService distributionBizService;

    protected Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 审核通过——免费
     *
     * @param memberActId 活动报名id
     * @param activityId  活动id
     * @return 是否审核通过（true/false）
     */
    public boolean verifyPassFree(String memberActId, String activityId) {
        try {

            // 更改活动报名状态 待支付
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {

                // 更改订单状态 待支付
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {
                    orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    orderFormService.update(orderForm);
                } else {
                    memberAct.setOrderId("");
                }
            }
            memberActService.update(memberAct);
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                payOrderBizService.updatePayBusiness(memberAct.getOrderId());
                messageOrderBizService.paySend(memberAct.getOrderId());
            } else {
                CounterfoilBusiness counterfoilBusiness = counterfoilBusinessService.findByBusinessId(memberActId);
                payOrderBizService.updatePayBusiness2(OrderType.ORDER_ACTIVITY.getCode(),
                        null, activityId, memberAct.getMemberId(), counterfoilBusiness.getCounterfoilId());
                messageOrderBizService.sendFree(OrderType.ORDER_ACTIVITY.getCode(),
                        activityId, memberActId, memberAct.getMemberId());
            }
            return true;
        } catch (Exception e) {
            logger.error("免费活动审核通过异常:{}", e);
            return false;
        }
    }

    /**
     * 审核通过——收费
     *
     * @param memberActId 活动报名id
     * @param activityId  活动id
     * @return 是否审核通过（true/false）
     */
    public boolean verifyPassNoFree(String memberActId, String activityId) {
        try {
            Activity activity = activityService.get(activityId);

            // 更改活动报名状态 待支付
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {

                // 更改订单状态 待支付
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {

                    // 如果订单状态等于已退款，则重新生成订单信息
                    if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {
                        String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(),
                                memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                        memberAct.setOrderId(orderId);
                    } else {
                        orderActivityBizService.updateActivityOrderStatus(memberAct.getOrderId(),
                                OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    }
                } else {
                    String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(),
                            memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    memberAct.setOrderId(orderId);
                }
            } else {
                String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(),
                        memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                memberAct.setOrderId(orderId);
            }
            memberActService.update(memberAct);
            notifySendService.sendApplyPass(activity, memberAct.getId(), memberAct.getMobile(),
                    memberAct.getMemberId(), ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
            return true;
        } catch (Exception e) {
            logger.error("收费活动审核通过异常:{}", e);
            return false;
        }
    }

    /**
     * 审核拒绝——免费
     *
     * @param memberActId 报名编号
     * @param activityId 活动编号
     * @return 是否审核成功（true/false）
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean verifyFailFree(String memberActId, String activityId) {
        try {
            // 更改活动报名状态 已拒绝
            MemberAct memberAct = memberActService.get(memberActId);

            // 如果是线下活动, 拒绝的时候, 如果已经是设置为已付款了, 那钱也要减少
            if (memberAct.getCounterfoilType().equals(CounterfoilType.TYPE_OFF_LINE.getCode()) && MemberAct.PAY_STATUS_YES.equals(memberAct.getPayStatus())) {
                try {
                    String actId = memberAct.getActId();
                    Activity act = activityService.get(actId);
//                    memberPersonalCountBizService.updateActivityNumMoney(act.getMember(), memberAct.getMemberId(), memberAct.getPayment(), false);
                    PartnerMember param = partnerMemberService.findByPartnerAndMember(act.getMember(), memberAct.getMemberId());
                    memberPersonalCountBizService.countOne(param);
                } catch (Exception e) {
                    logger.error("实时更新活动报名金额/数量异常 ", e);
                }
            }

            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
            memberAct.setPayStatus(MemberAct.PAY_STATUS_NO);
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {

                // 更改订单状态 其它
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {
                    orderForm.setStatus(OrderStatus.ORDER_STATUS_OTHER.getCode());
                    orderFormService.update(orderForm);
                } else {
                    memberAct.setOrderId("");
                }
            }
            memberActService.update(memberAct);

            // 免费活动
            refundOrderBizService.freeActivityReject(memberAct.getOrderId(), memberActId, o -> {
//                activityRefund(memberActId, 0d, null);
                return null;
            });

            messageOrderBizService.freeActivityRejectSend(memberActId, activityId, memberAct.getMemberId());
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("免费活动审核拒绝异常:{}", e);
            return false;
        }
    }

    @Transactional
    public void activityRefund(String memberActId, double payment, OrderForm orderForm) {
        try {
            String relationId = distributionBizService.activityApplyRefund(memberActId, orderForm);
            if (StringUtils.isNotEmpty(relationId)) {
                memberCopartnerDetailBizService.activityApplyRefund(relationId, memberActId, payment);
            }
        } catch (Exception e) {
            logger.error("活动退款，统计数据处理异常", e);
        }
    }

    /**
     * 审核拒绝——收费
     *
     * @param memberActId 报名编号
     * @return 是否审核成功（true/false）
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean verifyFailNoFree(String memberActId) {
        try {

            // 更改活动报名状态 已拒绝
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
            memberAct.setPayStatus(MemberAct.PAY_STATUS_NO);
            memberActService.update(memberAct);

            OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
            if (StringUtils.isEmpty(memberAct.getOrderId()) || orderForm == null) {
                refundOrderBizService.freeActivityReject(memberAct.getOrderId(), memberActId, o -> {
//                    activityRefund(memberActId, orderForm.getPayment(), orderForm);
                    return null;
                });
                messageOrderBizService.freeActivityRejectSend(memberActId, memberAct.getActId(),
                        memberAct.getMemberId());
                return true;
            } else {

                // 更改订单状态 其它
                if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())) {
                    Object responseData = refundBizService.refund(orderForm.getId(), null);
                    if (responseData != null) {
                        if (orderForm.getPaymentWay().equals(PaymentWay.ALI_PAY.getCode())) {
                            AliPayRefundResponse response = (AliPayRefundResponse) responseData;

                            // 状态码等于10000表示成功
                            if (response.getCode().equals(Constant.ALI_SUCCESS_CODE)) {
                                return refundBizService.activityRefundCallback(orderForm.getId(),
                                        response, PaymentWay.ALI_PAY.getCode(), memberAct.getId(), orderForm);
                            }
                        } else if (orderForm.getPaymentWay().equals(PaymentWay.WECHAT_PAY.getCode())) {
                            WechatPayRefundResponse response = (WechatPayRefundResponse) responseData;

                            // 退款成功
                            if (Constant.WECHAT_SUCCESS.equals(response.getReturnCode())
                                    && Constant.WECHAT_SUCCESS.equals(response.getResultCode())) {
                                return refundBizService.activityRefundCallback(orderForm.getId(),
                                        response, PaymentWay.WECHAT_PAY.getCode(), memberAct.getId(), orderForm);
                            }
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("收费活动审核拒绝异常", e);
            return false;
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean verifyFailNoFree2(String memberActId, Object object) {
        try {

            // 更改活动报名状态 已拒绝
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
            memberAct.setPayStatus(MemberAct.PAY_STATUS_NO);
            memberActService.update(memberAct);

            OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
            if (StringUtils.isEmpty(memberAct.getOrderId()) || orderForm == null) {
                refundOrderBizService.freeActivityReject(memberAct.getOrderId(), memberActId, o -> {
//                    activityRefund(memberActId, orderForm.getPayment(), orderForm);
                    return null;
                });
                messageOrderBizService.freeActivityRejectSend(memberActId, memberAct.getActId(),
                        memberAct.getMemberId());
                return true;
            } else {

                // 更改订单状态 其它
                if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())) {
                    if (orderForm.getPaymentWay().equals(PaymentWay.ALI_PAY.getCode())) {
                        AliPayQueryResponse queryResponse = (AliPayQueryResponse) object;
                        AliPayRefundResponse refundResponse = new AliPayRefundResponse();
                        MyBeanUtils.copyBeanNotNull2Bean(queryResponse, refundResponse);
                        return refundBizService.activityRefundCallback2(orderForm.getId(),
                                refundResponse, PaymentWay.ALI_PAY.getCode(), memberAct.getId(), orderForm);
                    } else if (orderForm.getPaymentWay().equals(PaymentWay.WECHAT_PAY.getCode())) {
                        WechatPayQueryResponse queryResponse = (WechatPayQueryResponse) object;
                        WechatPayRefundResponse refundResponse = new WechatPayRefundResponse();
                        MyBeanUtils.copyBeanNotNull2Bean(queryResponse, refundResponse);
                        return refundBizService.activityRefundCallback2(orderForm.getId(),
                                refundResponse, PaymentWay.WECHAT_PAY.getCode(), memberAct.getId(), orderForm);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("收费活动审核拒绝异常", e);
            return false;
        }
    }

    public SXSSFWorkbook exportExcel(List<MemberActOutput> memberActOutputs, String activityId) {
        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sheet0 = wb.createSheet("报名人员信息导出");
        appenCell(memberActOutputs, sheet0, activityId);
        return wb;
    }

    private void appenCell(List<MemberActOutput> memberActOutputs, Sheet sheet, String activityId) {
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        df.applyPattern("#.##");
        String[] memberInfoTitles = new String[]{
                "活动名称", "参与者昵称", "联系人", "公司", "职位", "身份证", "手机号", "微信号", "备注"
        };
        String[] applyInfoTitles = new String[]{
                "票据类型", "票据名称", "金额", "状态", "签到", "报名时间", "付款备注"
        };
        String[] fieldsTitle = null;

        GatherProject gatherProject = gatherProjectService.findByTargetId(activityId);
        if (null != gatherProject) {
            List<GatherForm> gatherForms = gatherFormService.findByProjectId(gatherProject.getId());
            List<String> formFields = LangUtils.transform(gatherForms, GatherForm::getTitle);
            fieldsTitle = formFields.toArray(new String[formFields.size()]);
        }
        Row titleRow = sheet.createRow(0);
        // 基本信息
        for (int i = 0; i < memberInfoTitles.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(memberInfoTitles[i]);
        }
        // 附属信息
        if (null != fieldsTitle) {
            for (int i = 0; i < fieldsTitle.length; i++) {
                Cell cell = titleRow.createCell(i + memberInfoTitles.length);
                cell.setCellValue(fieldsTitle[i]);
            }
        }
        int fieldLength = null == gatherProject ? 0 : fieldsTitle.length;

        // 票据信息
        for (int i = 0; i < applyInfoTitles.length; i++) {
            Cell cell = titleRow.createCell(i + memberInfoTitles.length + fieldLength);
            cell.setCellValue(applyInfoTitles[i]);
        }


        for (int i = 0; i < memberActOutputs.size(); i++) {
            Row row = sheet.createRow(i + 1);
            MemberActOutput output = memberActOutputs.get(i);

            // 基本信息
            String[] memberInfoValues = new String[]{
                    output.getActivityTitle(), null == output.getMember() ? "" : output.getMember().getRealname(),
                    output.getName(), output.getCompany(), output.getJobTitle(), output.getIdCard(), output.getMobile(),
                    output.getWechatNum(), output.getExtra()
            };

            for (int j = 0; j < memberInfoValues.length; j++) {
                Cell c0 = row.createCell(j);
                c0.setCellValue(memberInfoValues[j]);
            }

            if (null != gatherProject) {
                // 附属信息
                Map<String, Object> params = Maps.newHashMap();
                params.put("projectId", gatherProject.getId());
                params.put("targetId", output.getId());
                List<Map<String, Object>> gatherFormInfos = gatherFormInfoService.webListPage(params, null);
                for (int k = 0; k < gatherFormInfos.size(); k++) {
                    Map<String, Object> map = gatherFormInfos.get(k);
                    String[] fieldValues = null != map.get("fieldValue")
                            ? map.get("fieldValue").toString().split("maxIndex") : new String[0];
                    System.out.println();


                    for (int p = 0; p < fieldValues.length; p++) {
                        Cell c0 = row.createCell(p + memberInfoTitles.length);
                        c0.setCellValue(fieldValues[p]);
                    }
                }
            }

            // 票据信息
            String[] applyInfoValues = new String[]{
                    output.getCounterType(), output.getCounterName(), df.format(output.getCounterPrice()), output.getCheckStatusName(),
                    output.getSignInName(), DateUtils.formatDate(output.getCreateTime(), "yyyy-MM-dd HH:mm"), output.getRemarks()
            };

            for (int j = 0; j < applyInfoValues.length; j++) {
                Cell c0 = row.createCell(j + memberInfoTitles.length + fieldLength);
                c0.setCellValue(applyInfoValues[j]);
            }
        }
        System.out.println();
    }

    public void delete(MemberAct memberAct) {
        String orderId = memberAct.getOrderId();
        if (ActStatus.ACT_STATUS_CANCEL.getCode().equals(memberAct.getCheckStatus())) {
            if (StringUtils.isNotEmpty(orderId)) {
                orderFormService.delete(orderId);
            }
            memberActService.delete(memberAct.getId());
        }
    }
    public Integer getSigninMemberCountByMemberGroupId(List<String> memberGroupId,Map<String,Object> params){
        return memberActService.getSigninMemberCountByMemberGroupId(memberGroupId,params);
    }
}
